﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace zr
{
    public partial class Form1 : Form
    {
        private TcpListener listener = null;
        private TcpListener listener2 = null;
           private TcpListener listener3 = null;
           private TcpListener listener5 = null;
        private IPAddress ip = null;
        private IPHostEntry host = new IPHostEntry();
        private IPEndPoint myServer = null;
        private string hostname = Dns.GetHostName();
        private int port = 5761;

        private RichTextBox richTextBox = new RichTextBox();
       // private string command = null;
        private Thread thread = null;
        private Thread thread1 = null;
        private Thread thread2 = null;
        private Thread thread5 = null;
        private Thread threadConnected = null;
        private Thread threadTrans = null;//文件传输线程

        private static Point p;
        private FileStream fileStream;
        private DirectoryInfo dir;
        private Socket socket3;
        private Socket socket36;
        private TcpListener newListener = null;
        private Socket socket;
        private Socket socket2;
        private static bool started = false;
        private static string mousecmd = "";
        private static string picx;
        private static string picy;
        private static string zhujiip = "192.168.1.112";
        public Form1()
        {
            InitializeComponent();


        }

        private void str()
        {
            if (!started)
            {



            }
        }

        private void button1_Click(object sender, EventArgs e)
        {


            bool isrun = false;

            if (!isrun)
            {   thread = new Thread(new ThreadStart(shangxian));
                 thread.Start();
                /* thread2 = new Thread(new ThreadStart(target));
                 thread2.Start();*/
                thread5 = new Thread(new ThreadStart(ViewScreen));
                thread5.Start();
                
                Thread thread13 = new Thread(new ThreadStart(WriteToClient));
                thread13.Start();
                /* Thread thread135 = new Thread(new ThreadStart(str));
                thread135.Start();*/
                
                isrun = true;
                MessageBox.Show("已启动zr");
                //  str();
            }
            /* else if (socket != null)
            {
                if (socket.Connected & !isrun)
                {

                    //  WriteToClient(ref socket, tosned);
                   
                    isrun = true;
                    // thread13.Join();
                  
                }


            }
        }*/
        }

        private void shangxian()
        {
            //  host = Dns.GetHostByName(hostname);
            //    ip = host.AddressList[0];
            ip = IPAddress.Parse(zhujiip);
            //  myServer = new IPEndPoint(ip, port);
            listener2 = new TcpListener(ip, port);
            listener2.Start();
                    bool CanRead = false;
            while (true)
            {
                try
                {
                    bool ctred = true;
                     socket2 = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                    socket2 = listener2.AcceptSocket();
                    while(socket2.Connected)
                    {
                        if (ctred==true)
                        {
                            
                       
                        IPAddress ConnectIP = ((IPEndPoint)socket2.RemoteEndPoint).Address;
                        // MessageBox.Show(ConnectIP.ToString());
                        //  listBox1.Items.Add(ConnectIP.ToString());
                        //this.Refresh();
                        this.Invoke(new getdg(this.showdata), new object[] { ConnectIP.ToString() });
                            ctred = false;
                        } 
                        thread1 = new Thread(new System.Threading.ParameterizedThreadStart(iscnned));
                        thread1.Start(socket2);
                      /*  thread1 = new Thread(new System.Threading.ParameterizedThreadStart(rkeybord));
                        thread1.Start(socket2)*/
                      if (!CanRead)
                        {
                            Thread.Sleep(3000);
                        }
                   
                       // CanRead = false;
                        try
                        {
                            int f = 0;
                            byte[] byteMessage2 = new byte[1024];

                            f = (socket2).Receive(byteMessage2);
                            if (f > 0)
                            {


                                string command = System.Text.Encoding.UTF8.GetString(byteMessage2, 0, f);
                                int n = command.IndexOf("\r\n");
                                command = command.Substring(0, n);
                                this.Invoke(new getdg3(this.showdata3), new object[] { command });
                                //  break;
                              


                            }

                        }
                        catch (Exception)//连接后又断开引发异常
                        {
                            IPAddress ConnectIP2 = ((IPEndPoint)(socket2).RemoteEndPoint).Address;
                            this.Invoke(new getdg2(this.showdata2), new object[] { ConnectIP2.ToString() });
                            return;
                       
                            // return;
                        }
                        CanRead = false;
                    }

                }

                catch (Exception es)
                {
                    // return false;
                    MessageBox.Show(es.Message.ToString());
                }
            }
        }

        private void rkeybord(object cSocket)
        {
            while ((cSocket as Socket).Connected)
            {
                try
                {
                    int f = 0;
                    byte[] byteMessage2 = new byte[1024];

                    f = (cSocket as Socket).Receive(byteMessage2);
                    if (f>0)
                    {
                        
                  
                        string command = System.Text.Encoding.UTF8.GetString(byteMessage2, 0, f);
                        int n = command.IndexOf("\r\n");
                        command = command.Substring(0, n);
                        this.Invoke(new getdg3(this.showdata3), new object[] { command });
                        //  break;
                        /* if ( ss.IndexOf("s") == -1&f>500)
                     {
                        isConnected = false;
                     InitCommand();
                     return;
                     }*/

                        byteMessage2 = new byte[1024];
                     }

                }
                catch (Exception)//连接后又断开引发异常
                {
                    IPAddress ConnectIP = ((IPEndPoint)(cSocket as Socket).RemoteEndPoint).Address;
                    this.Invoke(new getdg2(this.showdata2), new object[] { ConnectIP.ToString() });
                    return;
                    /*isConnected = false;
                    InitCommand();*/
                   // return;
                }

            }
        }
        private void target()
        {
            ip = IPAddress.Parse(zhujiip);
            listener5 = new TcpListener(ip, port + 38);
            listener5.Start();
            socket36 = listener5.AcceptSocket();
            while (socket36.Connected)
            {
                try
                {
                    int f = 0;
                    byte[] byteMessage2 = new byte[1024];
                    
                        if ((f = socket36.Receive(byteMessage2)) > 0)
                       
                        {
                            string command = System.Text.Encoding.UTF8.GetString(byteMessage2, 0, f);
                       int n = command.IndexOf("\r\n");
                        command = command.Substring(0, n); 
                       this.Invoke(new getdg3(this.showdata3), new object[] {command});
                          //  break;
                        /* if ( ss.IndexOf("s") == -1&f>500)
                     {
                        isConnected = false;
                     InitCommand();
                     return;
                     }*/
                         
                   
                }

            }
                catch (Exception)//连接后又断开引发异常
                {
                    /*isConnected = false;
                    InitCommand();*/
                    return;
                }

            }
            /*isConnected = false;
            InitCommand();
            return;*/
        }
        public void iscnned(object cSocket)
        {
            while (true)
            {
                string sa = "";
                for (int i = sa.Length; i < 500; ++i)
                {
                    sa += "s";
                }
                 if (!WriteToServerforcnned(sa, cSocket as Socket))
                 {
                     IPAddress ConnectIP = ((IPEndPoint) (cSocket as Socket).RemoteEndPoint).Address;
                     this.Invoke(new getdg2(this.showdata2), new object[] {ConnectIP.ToString()});
                     return;
                 }
                Thread.Sleep(5000);
            }
        }

        public bool WriteToServerforcnned(string SendMessage, Socket cSocket)
        {
            string sendMsg = SendMessage + "\r\n";
            byte[] ToSend = System.Text.Encoding.UTF8.GetBytes(sendMsg.ToCharArray());
            try
            {
                cSocket.Send(ToSend);
                return true;
            }
            catch
            {
                return false;
            }
        }
        private delegate void getdg(string s);

        private void showdata(string s)
        {
            listBox1.Items.Add(s);
        }
        private delegate void getdg2(string s);

        private void showdata2(string s)
        {
            listBox1.Items.Remove(s);
        }
        private delegate void getdg3(string s);

        private void showdata3(string s)
        {
            //listBox1.Items.Add(s);
            richTextBox1.Text += s;
        }
        private void button2_Click(object sender, EventArgs e)
        {
            //  listBox1.Items.Add("127.0.0.5");
            //  WriteToClient("sssss");
            this.socket.Close();
            this.socket3.Close();
            this.socket2.Close();
            // 
            this.Dispose();
            this.Close();
           

        }
        private void WriteToClient()
        {
            ip = IPAddress.Parse(zhujiip);
            listener = new TcpListener(ip, port + 35);
            listener.Start();
            socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            socket = listener.AcceptSocket();
            started = true;
            while (socket.Connected)
            {



                string SendMessage = "|" + p.X.ToString() + "|" + p.Y.ToString() + "|" + picx + "|" + picy + "|" + mousecmd;
                //   Socket socket1 = socket as Socket;
                // string SendMessage = SendMessage.ToString();
                string sendMsg = "AOF" + SendMessage.ToString() + "|" + "EOF";
                byte[] ToSend = System.Text.Encoding.UTF8.GetBytes(sendMsg.ToCharArray());
                try
                {
                    socket.Send(ToSend);
                    //  return;
                }
                catch (Exception efException)
                {
                    MessageBox.Show(efException.Message.ToString());
                    //  return;
                }
                Thread.Sleep(500);
            }
        }

        private void pictureBox1_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                mousecmd = "mouseleft";
            }
            else if (e.Button == MouseButtons.Right)
            {
                mousecmd = "mouseright";
            }
        }

        private void pictureBox1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            mousecmd = "mousedouble";
        }

        private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
        {
            p = pictureBox1.PointToClient(Control.MousePosition);
            picx = pictureBox1.Width.ToString();
            picy = pictureBox1.Height.ToString();
        }
        private void ViewScreen()
        {
            MemoryStream ms = null;
            ip = IPAddress.Parse(zhujiip);
            listener3 = new TcpListener(ip, port + 3);
            listener3.Start();
            socket3 = listener3.AcceptSocket();
            while (socket3.Connected)
            {
                try
                {
                    byte[] by = new byte[1024];
                    int number = 0;
                    string s = "";
                    while (true)
                    {
                        if ((number = socket3.Receive(by)) > 0)
                        {
                            s = System.Text.Encoding.Unicode.GetString(by);
                            by = new byte[1024];
                            break;
                        }
                    }

                    s = s.Split('!')[0];
                    long len = 0;
                    if (long.TryParse(s, out len))
                    {
                        /// = long.Parse(s);



                        ms = new MemoryStream();
                        while (len > 0)
                        {
                            if ((number = socket3.Receive(by)) > 0)
                            {
                                ms.Write(by, 0, number);
                                len -= number;
                                by = new byte[1024];
                            }

                        }
                        /*    MemoryStream ms = new MemoryStream();
	                
                                       while((number = socket.Receive(by)) > 0)
                                       {
                                           ms.Write(by, 0, number);
                                        //   len -= number;
                                       }
                                 ms.Flush();*/



                        ms.Position = 0;
                        this.pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
                        this.pictureBox1.Image = Image.FromStream(ms);
                        ms.Flush();
                    }
                }
                catch (System.Exception ex)
                {
                    ms.Flush();
                    ms = new MemoryStream();
                }

            }
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            zhujiip = textBox1.Text.ToString();
        }
    }
}

